import { createStore } from 'redux'

// TS 注解
export type Todo = {
  id: number
  content: string
  done: boolean
}

export type TodoType = 'all' | 'active' | 'completed'

export type TodoState = {
  list: Todo[]
  type: TodoType
}

const initState: TodoState = {
  list: JSON.parse(localStorage.getItem('todo-list') || '[]'),
  // as 断言，告诉 TS 这是 TodoType
  type: (localStorage.getItem('todo-type') || 'all') as TodoType,
}

export type TodoAction =
  | { type: 'changeDoneById'; payload: number }
  | { type: 'delById'; payload: number }
  | { type: 'clearAllDone' }
  | { type: 'changeType'; payload: TodoType }
  | { type: 'addTodo'; payload: Todo }
  | { type: 'changeAll'; payload: boolean }

function reducer(state = initState, action: TodoAction) {
  switch (action.type) {
    case 'changeDoneById':
      return {
        ...state,
        list: state.list.map((item) => {
          if (item.id === action.payload) {
            return { ...item, done: !item.done }
          } else {
            return item
          }
        }),
      }
    case 'delById':
      return { ...state, list: state.list.filter((v) => v.id !== action.payload) }
    case 'clearAllDone':
      return { ...state, list: state.list.filter((v) => !v.done) }
    case 'changeType':
      return { ...state, type: action.payload }
    case 'addTodo':
      return { ...state, list: [action.payload, ...state.list] }
    case 'changeAll':
      return { ...state, list: state.list.map((item) => ({ ...item, done: action.payload })) }
    default:
      return state
  }
}

const store = createStore(reducer)

export default store
